/**
 * <b>项目名：</b>亲子分享-服务端项目<br/>
 * <b>包名：</b>com.saas.controller.production<br/>
 * <b>文件名：</b>APIController.java<br/>
 * <b>版本信息：</b>V1.0<br/>
 * <b>日期：</b>2015-4-9-下午05:14:17<br/>
 * <b>作者：</b><br/>
 * <b>Copyright (c)</b> 2015坚果(北京)科技有限公司-版权所有<br/>
 */
package com.saas.controller.v1;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.dao.DataAccessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.saas.exception.ServiceException;
import com.saas.service.APIService;
import com.saas.service.AuthorizationService;
import com.saas.service.saas.UserService;
import com.saas.util.Constant;
import com.saas.util.ResponseEntity;

/**
 *
 * <b>类名称：</b>UserController<br/>
 * <b>类描述：</b>用户接口控制器<br/>
 * <b>创建人：</b>Jack.xin<br/>
 * <b>修改人：</b><br/>
 * <b>修改时间：</b>2015-4-12 下午05:14:17<br/>
 * <b>修改备注：</b><br/>
 * @version 1.0.0<br/>
 *
 */
@RestController
@RequestMapping(value = "/api/saas/v1")
public class UserController {
	
	protected static Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private AuthorizationService authorizationService;
	
	@Autowired
	private APIService apiService;
	
	@Autowired
	private UserService userService;
	
	/**
	 * 
	 * login(登录)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * String
	 * @exception
	 * @since  1.0.0
	 */
	@RequestMapping(value = "/user/login")
	@Transactional(readOnly = true,rollbackFor = DataAccessException.class)//只读关闭，遇到DataAccessException异常回滚，如果不对异常进行处理，
	//该异常将一直向上抛出，直至抛出到页面
	public @ResponseBody String login(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String loginIdentifying = ServletRequestUtils.getStringParameter(request, Constant.User_loginIdentifying, null);
			String password = ServletRequestUtils.getStringParameter(request, Constant.user_password, null);
			String site = ServletRequestUtils.getStringParameter(request, Constant.user_site, "saas");
			String verifycode = ServletRequestUtils.getStringParameter(request, "verifycode", "");
			String appVersion = ServletRequestUtils.getStringParameter(request, "app_v", "-1");//当前软件版本号
			JSONObject json = new JSONObject();
			json.put(Constant.User_loginIdentifying, loginIdentifying);
			json.put(Constant.user_password, password);
			json.put(Constant.user_site, site);
			json.put("verifycode", verifycode);
			json.put(Constant.user_currentVersion, appVersion);
			JSONObject returnValue = userService.login(json);
			if(returnValue==null||StringUtils.isBlank(returnValue.getString(Constant.user_sessionToken))){
				responseEntity.setMsg("用户名或密码错误！");
				responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
			}else{
				responseEntity.setResult(returnValue);
				responseEntity.setMsg(Constant.API_CALL_STATUS_SUCCESS_MSG);
				responseEntity.setStatus(Constant.API_CALL_STATUS_SUCCESS);
			}

		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setMsg(e.getMessage());
			responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
		}
		request.setAttribute(Constant.CLIENT_RESPONSE, responseEntity);
		return null;
	}
	
	/**
	 * 
	 * register(用户注册)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * String
	 * @exception
	 * @since  1.0.0
	 */
	@RequestMapping(value = "/user/register")
	public @ResponseBody String register(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			
			String username = ServletRequestUtils.getStringParameter(request, Constant.user_username, null);
			String password = ServletRequestUtils.getStringParameter(request, Constant.user_password, null);
			String mobile = ServletRequestUtils.getStringParameter(request, Constant.user_phonenum, null);
			String nickname = ServletRequestUtils.getStringParameter(request, "nickname", null);
			int gender = ServletRequestUtils.getIntParameter(request, "gender", -1);//性别,0男宝 1女宝
			String site = ServletRequestUtils.getStringParameter(request, Constant.user_site, "saas");//网站名
			String siteUserId = ServletRequestUtils.getStringParameter(request, Constant.user_siteUserId, "");//站点
			int type = ServletRequestUtils.getIntParameter(request, "type", 0); //用户类型，默认0 普通用户，1达人用户，2专家用户
			String appVersion = ServletRequestUtils.getStringParameter(request, "app_v", "-1");//当前软件版本号
			String fromSource = ServletRequestUtils.getStringParameter(request, "fromSource", "");//注册来源：weixin,ios,android
			
			String birthday = ServletRequestUtils.getStringParameter(request, Constant.user_birthday, "");//站点
			String id_no = ServletRequestUtils.getStringParameter(request, Constant.user_id_no, "");//站点
			String realname = ServletRequestUtils.getStringParameter(request, Constant.user_realname, "");//站点
			String description = ServletRequestUtils.getStringParameter(request, Constant.user_description, "");//站点
			
			
			JSONObject user = new JSONObject();
			user.put(Constant.user_regVersion, appVersion);//注册版本
			user.put(Constant.user_currentVersion, appVersion);//当前版本
			user.put(Constant.user_username, username);
			user.put(Constant.user_password, password);
			user.put(Constant.user_phonenum, mobile);
			user.put("type", type);
			user.put("fromSource", fromSource);
			user.put("nickname", nickname);
			user.put("gender", gender);
			user.put(Constant.user_site, site);
			user.put(Constant.user_siteUserId, siteUserId);
			user.put(Constant.user_birthday, birthday);
			user.put(Constant.user_id_no, id_no);
			user.put(Constant.user_realname, realname);
			user.put(Constant.user_description, description);
			
			JSONObject jsonObject = userService.register(user);
			responseEntity.setResult(jsonObject);
			responseEntity.setMsg(Constant.API_CALL_STATUS_SUCCESS_MSG);
			responseEntity.setStatus(Constant.API_CALL_STATUS_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setMsg(e.getMessage());
			responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
		}
		request.setAttribute(Constant.CLIENT_RESPONSE, responseEntity);
		return null;
	}	
	
	
	/**
	 * 
	 * modify(用户信息修改)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * String
	 * @exception
	 * @since  1.0.0
	 */
	@RequestMapping(value = "/user/modify")
	public @ResponseBody String modify(
			HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String userId = ServletRequestUtils.getStringParameter(request, "userId", null);
			String username = ServletRequestUtils.getStringParameter(request, Constant.user_username, null);
//			String password = ServletRequestUtils.getStringParameter(request, Constant.user_password, null);
//			String mobile = ServletRequestUtils.getStringParameter(request, Constant.user_mobilePhoneNumber, null);
			String iconUrl = ServletRequestUtils.getStringParameter(request, "iconUrl", null);
			int stage = ServletRequestUtils.getIntParameter(request, "stage", -1);
			//int level = ServletRequestUtils.getIntParameter(request, "level", -1);
			//int levelScore = ServletRequestUtils.getIntParameter(request, "levelScore", -1);
			//int score = ServletRequestUtils.getIntParameter(request, "score", -1);
			String babyWillBirthday = ServletRequestUtils.getStringParameter(request, "babyWillBirthday", null);
			String babyBirthday = ServletRequestUtils.getStringParameter(request, "babyBirthday", null);
			int babyGender = ServletRequestUtils.getIntParameter(request, "babyGender", -1);
			String userBirthday = ServletRequestUtils.getStringParameter(request, "userBirthday", null);
			String address = ServletRequestUtils.getStringParameter(request, "address", null);
			int gender = ServletRequestUtils.getIntParameter(request, "gender", -1);//性别：0男 1女
			JSONObject user = new JSONObject();
			user.put(Constant.OBJECTID, userId);
			if(StringUtils.isNotBlank(username)) user.put(Constant.user_username, username);
			//if(StringUtils.isNotBlank(password)) user.put(Constant.user_password, password);
			//user.put(Constant.user_mobilePhoneNumber, mobile);
			//以下业务判断与安卓接口调试时修改 lisha 2015-7-20
			if(StringUtils.isNotBlank(iconUrl)) {user.put("iconUrl", iconUrl);}
			if(StringUtils.isNotBlank(babyWillBirthday)){  user.put("babyWillBirthday", babyWillBirthday);}
			if(StringUtils.isNotBlank(babyBirthday)) {		user.put("babyBirthday", babyBirthday);}
			if(StringUtils.isNotBlank(userBirthday)) {		
				user.put("userBirthday", userBirthday);
				}
			if(StringUtils.isNotBlank(address)) 	 {		user.put("address", address);}
			
			if(babyGender > -1) user.put("babyGender", babyGender);
			
			if(StringUtils.isNotBlank(babyWillBirthday)){
				stage=1;
			}else if (StringUtils.isNotBlank(babyBirthday)){
				stage=2;
			}
			user.put("stage", stage);
			/*if(level > -1) 		user.put("level", level);
			if(levelScore > -1) user.put("levelScore", levelScore);
			if(score > -1) 		user.put("score", score);*/
			if(gender > -1) 	user.put("gender", gender);
			JSONObject jsonObject = userService.modify(user);
			responseEntity.setResult(jsonObject);
			responseEntity.setMsg(Constant.API_CALL_STATUS_SUCCESS_MSG);
			responseEntity.setStatus(Constant.API_CALL_STATUS_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setMsg(e.getMessage());
			responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
		}
		request.setAttribute(Constant.CLIENT_RESPONSE, responseEntity);
		return null;
	}
	
	/**
	 * 
	 * passwordModify(修改密码)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * String
	 * @exception
	 * @since  1.0.0
	 */
	@RequestMapping(value = "/user/password/modify")
	public @ResponseBody String passwordModify(@RequestBody String body,HttpServletRequest request, HttpServletResponse response) throws IOException{
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String userId = ServletRequestUtils.getStringParameter(request, "userId", null);
			String password = ServletRequestUtils.getStringParameter(request, "password", null); 
			String oldPassword = ServletRequestUtils.getStringParameter(request, "oldPassword", null);
			String sessionToken = ServletRequestUtils.getStringParameter(request, Constant.user_sessionToken, null);
			String site = ServletRequestUtils.getStringParameter(request, Constant.user_site, "saas");
			JSONObject jsonObject = userService.modifyPassword(userId, sessionToken, oldPassword, password,site);
			responseEntity.setResult(jsonObject);
			responseEntity.setMsg(Constant.API_CALL_STATUS_SUCCESS_MSG);
			responseEntity.setStatus(Constant.API_CALL_STATUS_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setMsg(e.getMessage());
			responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
		}
		request.setAttribute(Constant.CLIENT_RESPONSE, responseEntity);
		return null;
	}
	
	/**
	 * 
	 * getUser(获取用户信息)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * String
	 * @exception
	 * @since  1.0.0
	 */
	@RequestMapping(value = "/user/get")
	public @ResponseBody String getUser(HttpServletRequest request, HttpServletResponse response) throws IOException{
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String userId=ServletRequestUtils.getStringParameter(request, "userId", null);
			JSONObject jsonObject = userService.getUserById(userId);
			responseEntity.setResult(jsonObject);
			responseEntity.setMsg(Constant.API_CALL_STATUS_SUCCESS_MSG);
			responseEntity.setStatus(Constant.API_CALL_STATUS_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setMsg(e.getMessage());
			responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
		}
		request.setAttribute(Constant.CLIENT_RESPONSE, responseEntity);
		return null;
	}
	
	
	/**
	 * sendMobileCode(发送手机验证码)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * String
	 * @exception
	 * @since  1.0.0
	 */
	@RequestMapping(value = "/user/mobile/send")
	public @ResponseBody String sendMobileCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String userId = ServletRequestUtils.getStringParameter(request, "userId", "");
			String mobile = ServletRequestUtils.getStringParameter(request, "mobile", "");
			userService.sendMobleVerifyCode(mobile);
			responseEntity.setMsg(Constant.API_CALL_STATUS_SUCCESS_MSG);
			responseEntity.setStatus(Constant.API_CALL_STATUS_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setMsg(e.getMessage());
			responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
		}
		request.setAttribute(Constant.CLIENT_RESPONSE, responseEntity);
		return null;
	}
	
	/**
	 * userMobileBind(用户手机号绑定)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * String
	 * @exception
	 * @since  1.0.0
	 */
	@RequestMapping(value = "/user/mobile/bind")
	public @ResponseBody String userMobileBind(HttpServletRequest request, HttpServletResponse response) throws IOException{
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String userId = ServletRequestUtils.getStringParameter(request, "bindUserId", "");
			String mobile = ServletRequestUtils.getStringParameter(request, "mobile", "");
			String code = ServletRequestUtils.getStringParameter(request, "code", "");
			responseEntity.setResult(userService.userMobileBind(userId, mobile, code));
			responseEntity.setMsg(Constant.API_CALL_STATUS_SUCCESS_MSG);
			responseEntity.setStatus(Constant.API_CALL_STATUS_SUCCESS);
		} catch (ServiceException e) {
			responseEntity.setMsg(e.getMessage());
			responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setMsg(e.getMessage());
			responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
		}
		request.setAttribute(Constant.CLIENT_RESPONSE, responseEntity);
		return null;
	}
	
	/**
	 * userMobileBind(用户手机号绑定)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * String
	 * @exception
	 * @since  1.0.0
	 */
	@RequestMapping(value = "/user/mobile/unbind")
	public @ResponseBody String userMobileunBind(HttpServletRequest request, HttpServletResponse response) throws IOException{
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String userId = ServletRequestUtils.getStringParameter(request, "bindUserId", "");
			String mobile = ServletRequestUtils.getStringParameter(request, "mobile", "");
			String code = ServletRequestUtils.getStringParameter(request, "code", "");
			responseEntity.setResult(userService.userMobileunBind(userId, mobile, code));
			responseEntity.setMsg(Constant.API_CALL_STATUS_SUCCESS_MSG);
			responseEntity.setStatus(Constant.API_CALL_STATUS_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setMsg(e.getMessage());
			responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
		}
		request.setAttribute(Constant.CLIENT_RESPONSE, responseEntity);
		return null;
	}
	
	
	/**
	 * resetPwd(手机号重置密码)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * String
	 * @exception
	 * @since  1.0.0
	 */
	@RequestMapping(value = "/user/password/reset")
	public @ResponseBody String resetPwd(HttpServletRequest request, HttpServletResponse response) throws IOException{
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String mobile = ServletRequestUtils.getStringParameter(request, "mobile", "");
			String code = ServletRequestUtils.getStringParameter(request, "code", "");
			String password = ServletRequestUtils.getStringParameter(request, "password", "");
			responseEntity.setResult(userService.resetPwd(mobile, code, password));
			responseEntity.setMsg(Constant.API_CALL_STATUS_SUCCESS_MSG);
			responseEntity.setStatus(Constant.API_CALL_STATUS_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setMsg(e.getMessage());
			responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
		}
		request.setAttribute(Constant.CLIENT_RESPONSE, responseEntity);
		return null;
	}
	
	/**
	 * 用户个人信息获取
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * String
	 * @exception
	 * @since  1.0.0
	 */
	@RequestMapping(value = "/user/base/get")
	public @ResponseBody String baseGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String viewUserId = ServletRequestUtils.getStringParameter(request, "viewUserId", "");
			String[] viewUserIds = viewUserId.split(",");
//			responseEntity.setResult(userService.getUserBase(viewUserIds));
			responseEntity.setMsg(Constant.API_CALL_STATUS_SUCCESS_MSG);
			responseEntity.setStatus(Constant.API_CALL_STATUS_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.setMsg(e.getMessage());
			responseEntity.setStatus(Constant.API_CALL_STATUS_ERROR_EXCEPTION);
		}
		request.setAttribute(Constant.CLIENT_RESPONSE, responseEntity);
		return null;
	}
	

}
